<?php

namespace app\api\controller;

use app\admin\model\pro\Light;
use app\admin\model\Sales;
use app\admin\model\Salesin;
use app\common\controller\Api;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *  审批
 */
class Sale extends Api
{
    /**
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = [];
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (array_key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else if (array_key_exists($this->excludeFields, $params)) {
            unset($params[$this->excludeFields]);
        }
        return $params;
    }

    public function demo(){
        echo '管理员id是: ' . $this->auth->id ;
        echo '审批';
    }

    //销售单填报
    public function add(){
        $data = $this->request->post();
        $this->model = new Sales();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;
        // 业绩归属人
        $params['saler_id'] = isset($params['saler_id']) ? $params['saler_id'] : $this->auth->id;

        $params['num'] = intval($params['num'] );
        $params['weight'] = floatval($params['weight'] );

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            // 销售出库:
            // demo
            $sale = [
                'factory_id' => $this->auth->factory_id ,
                'storea_id' => $params['storea_id'],      //   出栏兔库 , 仔兔库, 生长兔库      3种销售出库
                'field2' => $params['pinxi_id'],              //   品系
                'group_id'=> $params['group_id'],        //
                'batch_id'=> $params['batch_id'],
                'num' =>        $params['num'],        // 出栏 总数
                'cal_num' =>    -$params['num'],
                'cal' => "销售出库",
                'field1' => "",
                'stock' => "",                                              //  生长兔库+bnum
                'price' => abs( floatval($params['price']) ),              //  销售单价格
                'total' => abs( floatval($params['total']) ),              //  销售单价格
                // 出栏均重   特殊属性,计算成本用?
                'createtime' => date("Y-m-d H:i:s")
            ];
            $salelog = Db::name("storepro")->insert($sale);


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    // 生物采购单
    public function salesin(){
        $data = $this->request->post();
        $this->model = new Salesin();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;
        // 业绩归属人
        $params['saler_id'] = isset($params['saler_id']) ? $params['saler_id'] : $this->auth->id;

        $params['num'] = intval($params['num'] );
        $params['weight'] = floatval($params['weight'] );

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            // 销售出库:
            // demo
            $sale = [
                'factory_id' => $this->auth->factory_id ,
                'storea_id' => $params['storea_id'],      //   出栏兔库 , 仔兔库, 生长兔库      3种销售出库
                'field2' =>  $params['pinxi_id'],              //   品系
                'group_id'=> $params['group_id'],        //
                'batch_id'=> $params['batch_id'],
                'num' =>        $params['num'],        // 出栏 总数
                'cal_num' =>    $params['num'],
                'cal' => "销售入库",
                'field1' => "",
                'stock' => "",                                              //  生长兔库+bnum
                'price' => abs( floatval($params['price']) ),              //  销售单价格
                'total' => abs( floatval($params['total']) ),              //  销售单价格
                // 出栏均重   特殊属性,计算成本用?
                'createtime' => date("Y-m-d H:i:s")
            ];
            $salelog = Db::name("storepro")->insert($sale);


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }
    //销售单列表
    public function orderlist(){
        $model = new Sales();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
//            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();
//echo Db::getLastSql(); die;
        $this->success('成功', $data);
    }

    // 采购列表
    public function buylist(){
        $model = new Salesin();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            // $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();
//echo Db::getLastSql(); die;
        $this->success('成功', $data);
    }

    //销售单审批列表
    public function checklist(){}
    //销售单审批
    public function checkdo(){}


    public function edit(){}
    public function del(){}
    public function todoa(){}


}